from django.http import HttpResponse
from ipywidgets.embed import html_template

from common.models import Customer
from django.shortcuts import render
from django.template import engines
django_engine=engines["django"]
template=django_engine.from_string(html_template)

def listorders(request):
    return HttpResponse("下面是系统中所有的订单信息...")

def listcustomers(request):
    #返回一个QuerySet对象,包含所有记表的记录
    #每条记录都是一个dict对象
    #key是字段名,value是字段值
    qs=Customer.objects.values()

    #定义返回字符
    retStr=""
    for customer in qs:
        for name,value in customer.items():
            retStr+=f'{name}:{value}|'

        #<br>换行
        retStr+="<br>"

    return HttpResponse(retStr)
def listcustomers1(request):
    #返回一个QuerySet对象,包含所有记表的记录
    #每条记录都是一个dict对象
    #key是字段名,value是字段值
    qs=Customer.objects.values()
    #检查url中是否有参数
    ph=request.GET.get('phonenumber',None)
    #添加过滤条件
    if ph:
        qs=qs.filter(phonenumber=ph)
    #定义返回字符
    retStr=""
    for customer in qs:
        for name,value in customer.items():
            retStr+=f'{name}:{value}|'

        #<br>换行
        retStr+="<br>"

    return HttpResponse(retStr)

#先定义html模板
html_template='''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
table {
    border-collapse:collapse;
}
th,td{
    padding:8px;
    text-align:left;
    border-bottom:1px solid #ddd;
    }
</style>
</head>
    <body>
        <table>
        <tr>
        <th>id</th>
        <th>姓名</td>
        <th>电话号码</td>
        <th>地址</td>
        </tr>
        # %s
        #利用django模板
        {% for customer in customers %}
            <tr>
            {% for name,value in customer.items %}
            <td>{{value}}</td>
            {%endfor%}
            </tr>
        {% endfor%}
        
        
        
        
        </table>



</html>
'''


def listcustomers2(request):
    #返回一个queryset对象,包含所有的表记录
    qs=Customer.objects.values()
    #检查url中是否有参数phonenumber
    ph=request.GET.get("phonenumber",None)
    #如果有,添加过滤条件
    if ph:
        qs=qs.filter(phonenumber=ph)
    #生成html末班中要插入的html片段内容
    tableContent=""
    for customer in qs:
        tableContent+='<tr>'

        for name ,value in customer.items():
            tableContent+=f'<td>{value}<td>'

        tableContent+="</tr>"

    return HttpResponse(html_template%tableContent)

def listcustomers3(request):
    qs=Customer.objects.values()
    ph=request.GET.get("phonenumber",None)
    if ph:
        qs=qs.filter(phonenumber=ph)
    rendered=template.render({'customers':qs})
    return HttpResponse(rendered)


